package com.dcm.item.service.impl;

import com.dcm.common.constant.Constants;
import com.dcm.common.exception.MyException;
import com.dcm.item.entity.SpecificationEntity;
import com.dcm.item.mapper.SpecMapper;
import com.dcm.item.service.SpecService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * Classname: SpecServiceImpl
 * @Author  Mengxiangjian
 * Date: 2021/3/22 14:14
 * Version V 1.0
 */
@Service
public class SpecServiceImpl implements SpecService {

    @Autowired
    private SpecMapper specMapper;

    @Override
    public List<SpecificationEntity> findAll() {
        return specMapper.findAll();
    }
    @Override
    public void add(SpecificationEntity tbspecification)  {
        checkSpec(tbspecification);
        specMapper.add(tbspecification);
    }

    @Override
    public void delete(Long id)  {
        specMapper.delete(id);
    }

    @Override
    public void update(SpecificationEntity tbspecification)  {
        checkSpec(tbspecification);
        specMapper.update(tbspecification);
    }

    @Override
    public SpecificationEntity find(String name)  {
        if (StringUtils.isBlank(name)) {
            throw new MyException(Constants.SpecificaErroMsg.SPECIFICATIONNAMETONULL);
        }
        return specMapper.find(name);
    }

    @Override
    public void deletes(@RequestParam("list") List<Long> ids)  {
        for (Long id : ids) {
            specMapper.delete(id);
        }
    }

    @Override
    public PageInfo<SpecificationEntity> findPage(Integer currentPage, Integer pageSize) {
        if (currentPage == null || pageSize == null) {
            throw new MyException(Constants.ResponseMsg.PAGE_PARAMS_NOT_NULL);
        }

        PageHelper.startPage(currentPage, pageSize);
        List<SpecificationEntity> list = specMapper.findAll();
        //用PageInfo对结果进行包装
        PageInfo<SpecificationEntity> page = new PageInfo<>(list);

        return page;
    }

    public static void checkSpec(SpecificationEntity specificationEntity)  {
        if (StringUtils.isBlank(specificationEntity.getName())) {
            throw new MyException(Constants.SpecificaErroMsg.SPECIFICATIONNAMETONULL);
        }
        if (StringUtils.isBlank(specificationEntity.getType())) {
            throw new MyException(Constants.SpecificaErroMsg.SPECIFICATIONTYPETONULL);
        }
        if (StringUtils.isBlank(specificationEntity.getAttr())) {
            throw new MyException(Constants.SpecificaErroMsg.SPECIFICATIONSHOPTONULL);
        }
    }
}
